/*   
* Project: OSMP
* FileName: CollectorServer.java
* version: V1.0
*/
package tk.mybatis.springboot.collector;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.log4j.Logger;

/**
 * Description:
 * 
 * @author: wangkaiping
 * @date: 2018年3月6日 下午3:31:14上午10:51:30
 */
public class CollectorServer extends Thread {
	private static Logger logger = Logger.getLogger(CollectorServer.class);
	private static CollectorServer server;
	private ServerSocket serverSocket;
	private ExecutorService executorService;
	private final int POOL_SIZE = 10;
	//服务器监听端口默认9527
	private int port;

	private static final ConcurrentHashMap<String, String> deviceMapping = new ConcurrentHashMap<>();

	public static String getDevice(String key) {
		return deviceMapping.get(key);
	}

	public static Map<String,String> getDeviceMapping() {
		return deviceMapping;
	}
	
	public static void setDeviceMapping(String key, String deviceId) {
		if (!deviceMapping.containsKey(key)) {
			deviceMapping.put(key, deviceId);
			logger.debug("--------------set deviceMapping key: " + key + " deviceId: " + deviceId + "------------");
		}
	}

	public static void cleanDeviceMapping() {
		if (!deviceMapping.isEmpty()) {
			deviceMapping.clear();
			logger.debug("-------------clean deviceMapping success--------------");
		}
	}

	/**
	 * @return the port
	 */
	public int getPort() {
		return port;
	}

	/**
	 * @param port
	 *            the port to set
	 */
	public void setPort(int port) {
		this.port = port;
	}

	private CollectorServer() {
	}

	public static CollectorServer getInstance() {
		if (null == server) {
			server = new CollectorServer();
		}
		return server;
	}

	private void init(int port) throws IOException {
		serverSocket = new ServerSocket(port);
		executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * POOL_SIZE);
		logger.debug("-------------------采集服务已启动----------------");
	}

	private void startExecute() {
		while (true) {
			Socket socket = null;
			try {
				socket = serverSocket.accept();
				executorService.execute(new ParseHandler(socket));
				logger.debug("-------------------监听到新的客户端连接----------------");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 入口方法<br>
	 * 一个核心mis只有一个ip和端口
	 * 
	 */
	@Override
	public void run() {

		try {
			server.init(port);
			server.startExecute();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}
